package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.FfindGoodsDbHelper;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.widget.LetterIndexView;
import com.gdk.ksoft.data.entry.tables.GoodsGroupTable;
import com.gdk.ksoft.ui.works.adapters.GoodsGroupAdapter;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 按分组查找的页面
 */
public class FindbyGroupActivity extends Activity  implements LetterIndexView.OnLetterClickListener{

    @ViewInject(R.id.pfindbyGroup_txtLetterTip)private TextView txtLetterTip;//字母索引器显示器
    @ViewInject(R.id.pfindbyGroup_livLetter)private LetterIndexView livLetter;//字母索引指示器
    @ViewInject(R.id.pfindbyGroup_lvGroup)private ListView lvGroup;//品牌展示表格
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findby_group);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        initActivity();//初始化页面数据
    }

    @Override
    public void onLetterClick(int selectedIndex, String letter) {
        GoodsGroupAdapter adapter = (GoodsGroupAdapter)lvGroup.getAdapter();
        if(adapter == null) return;
        List<GoodsGroupTable> list = adapter.getSourceList();
        for(int i=0;i<list.size();i++){
            GoodsGroupTable item = list.get(i);
            if(!TextUtils.isEmpty(item.mc)){
                if(letter.equals("#")){
                    if(!getFirstLetter(item.mc.charAt(0)).matches("[A-Za-z]")){
                        lvGroup.setSelection(i);
                        return;
                    }
                    continue;
                }else if(getFirstLetter(item.mc.charAt(0)).equals(letter)){
                    lvGroup.setSelection(i);
                    return;
                }
            }
        }
        selectFirstItem();//选中第一项作为显示首字母项
    }

    /**
     * 初始化页面数据
     */
    public void initActivity() {
        livLetter.setTxtIndictor(txtLetterTip);
        livLetter.setOnLetterIndexChangedListener(this);
        lvGroup.setSelected(true);
        lvGroup.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                selectFirstItem();//选中第一项作为显示首字母项
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        lvGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GoodsGroupTable item = (GoodsGroupTable)lvGroup.getItemAtPosition(position);
                Intent intent = new Intent();
                intent.putExtra("groupId",item.id);//传递分组ID
                FindbyGroupActivity.this.setResult(Activity.RESULT_OK,intent);
                FindbyGroupActivity.this.finish();
                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            }
        });
        requestGoodsGroupData(this);//请求商品品牌数据
    }

    /***
     * 选中第一项作为显示首字母项
     */
    public void selectFirstItem(){
        try {
            int visiablePos = lvGroup.getFirstVisiblePosition();
            GoodsGroupAdapter adapter = (GoodsGroupAdapter) lvGroup.getAdapter();
            if (adapter == null) return;//没有数据存在
            List<GoodsGroupTable> list = adapter.getSourceList();
            String letter = getFirstLetter(list.get(visiablePos).mc.charAt(0));
            int index = LetterIndexView.LETTERS.indexOf(letter);
            if(index == -1 || index == LetterIndexView.LETTERS.length()-1)
                index = LetterIndexView.LETTERS.length()-1;
            livLetter.setSelectedIndex(index);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 请求商品分组数据
     */
    public void requestGoodsGroupData(final Context context){
        new AsyncTask<Void, Void, Void>() {
            private ProgressDialog dialog = null;
            private String errorMessage = null;
            private List<GoodsGroupTable> list = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    list = FfindGoodsDbHelper.findAllGoodsGroups(dbUtils);
                    if(list!=null) sortGoodsBrandList(list);//对集合进行排序
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errorMessage != null){
                    Toast.makeText(context,"初始化失败!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(list == null||list.size()<=0) return;//没有分组数据
                lvGroup.setAdapter(new GoodsGroupAdapter(context,list));
                selectFirstItem();//选中第一项作为显示首字母项
            }
        }.execute();
    }

    /**
     * 给商品分组名称进行字母排序
     * @param list
     */
    public void sortGoodsBrandList(List<GoodsGroupTable> list){
        Collections.sort(list, new Comparator<GoodsGroupTable>() {
            @Override
            public int compare(GoodsGroupTable lhs, GoodsGroupTable rhs) {
                String firstLetter = getFirstLetter(lhs.mc.charAt(0));
                String secondLetter = getFirstLetter(rhs.mc.charAt(0));
                if (firstLetter != null && secondLetter != null) {
                    return firstLetter.toCharArray()[0] - secondLetter.toCharArray()[0];
                }
                return 0;
            }
        });
    }

    /**
     * 获得字符串的首字母
     * @param ch
     * @return
     */
    public String getFirstLetter(char ch){
        String[] arr = PinyinHelper.toHanyuPinyinStringArray(ch);
        if(arr == null || arr.length == 0) return "#";
        return arr[0].toUpperCase().substring(0,1);
    }


    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pfindbyGroup_imgBack})
    public void OnBackClick(View view) {
        goBack();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
